const express = require("express");
const router = express.Router();
const {
  login,
  getAllUserInfo,
  getAllAdminInfo,
  addAdmin,
  updateAdmin,
  deleteAdmin,
  getPermission,
  assignPermission,
  deleteAdmins,
} = require("../../router_handler/admin/user");

// 登录路由
router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  const result = await login(username, password);
  res.send(result);
});
// 获取用户信息
router.get("/info", async (req, res) => {
  const { username, id } = req.auth;
  const result = await getAllUserInfo(id, username, req);
  res.send(result);
});
// 登出
router.post("/logout", (req, res) => {
  res.send({
    code: 200,
    message: "成功",
    data: null,
    ok: true,
  });
});
// 获取所有管理员信息
router.get("/allAdmin/:page/:limit", async (req, res) => {
  const page = req.params.page;
  const limit = req.params.limit;
  const keyword = req.query.username;
  const offset = (page - 1) * limit;
  const result = await getAllAdminInfo(page, limit, keyword, offset);
  res.send(result);
});
// 添加admin用户
router.post("/save", async (req, res) => {
  const { username, password } = req.body;
  const result = await addAdmin(username, password);
  res.send(result);
});
// 修改用户
router.put("/update", async (req, res) => {
  const { id, username } = req.body;
  const result = await updateAdmin(id, username);
  res.send(result);
});
// 删除用户
router.delete("/remove/:id", async (req, res) => {
  const id = req.params.id;
  const result = await deleteAdmin(id);
  res.send(result);
});
// 获取权限
router.get("/toAssign/:id", async (req, res) => {
  const id = req.params.id;
  const result = await getPermission(id);
  res.send(result);
});
// 分配权限
router.post("/doAssignRole", async (req, res) => {
  const { userId, roleId } = req.body;
  const result = await assignPermission(userId, roleId);
  res.send(result);
});
// 批量删除用户
router.post("/batchRemove", async (req, res) => {
  const { id } = req.body;
  const result = await deleteAdmins(id);
  res.send(result);
});
module.exports = router;
